package main

import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
    "log"
    "time"
)
//https://www.jianshu.com/p/9b5cd762e256
var MysqlDb *sql.DB
var MysqlDbErr error

const (
    USER_NAME = "root"
    PASS_WORD = "123456"
    HOST      = "192.168.56.1"
    PORT      = "3306"
    DATABASE  = "warning"
    CHARSET   = "utf8"
)


func StructInsert() {

    ret,err := MysqlDb.Exec("insert INTO warning(user_id,nickname,avatar,message_info,message_time,capture_timestamp) values(?,?,?,?,?,?)","wx_789","小张","http://xxx","内容测试1","2020-06-05 9:30:20","2020-06-05 10:50:20")
    if err != nil {
        fmt.Println(err)
    }

    fmt.Print("ddddd")
    //插入数据的主键id
    lastInsertID,_ := ret.LastInsertId()
    fmt.Println("LastInsertID:",lastInsertID)

    //影响行数
    rowsaffected,_ := ret.RowsAffected()
    fmt.Println("RowsAffected:",rowsaffected)

}




// 初始化链接
func main() {

    dbDSN := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s", USER_NAME, PASS_WORD, HOST, PORT, DATABASE, CHARSET)

    // 打开连接失败
    MysqlDb, MysqlDbErr = sql.Open("mysql", dbDSN)
    //defer MysqlDb.Close();
    if MysqlDbErr != nil {
        log.Println("dbDSN: " + dbDSN)
        panic("数据源配置不正确: " + MysqlDbErr.Error())
    }

    // 最大连接数
    MysqlDb.SetMaxOpenConns(100)
    // 闲置连接数
    MysqlDb.SetMaxIdleConns(20)
    // 最大连接周期
    MysqlDb.SetConnMaxLifetime(100*time.Second)

    if MysqlDbErr = MysqlDb.Ping(); nil != MysqlDbErr {
        panic("数据库链接失败: " + MysqlDbErr.Error())
    }
    
    StructInsert()


}